<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>上传页</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="/static/favicon.ico">
    <script src="/static/js/jquery.min.js?v=2.1.4"></script>

    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <script src="/static/layui/layui.2.7.6.js"></script>
    <script src="/static/js/base.js"></script>

</head>
<body>

<div class="layui-fluid" style="margin-top: 10px">
    <div class="layui-card">
        <form class="layui-form layui-form-pane" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">分类选择</label>
                <div class="layui-input-inline">
                    <select name="category_id" id="category">
                        <option value="0">默认</option>

                    </select>
                </div>
            </div>
        </form>
        <div class="layui-card-body">
            <div class=" layui-upload-drag" style="width: 90%;padding: 20px 4%">

                    <div class="chooseFile">
                        <i class="layui-icon"></i>
                        <p>点击上传，或将文件拖拽到此处</p>
                    </div>
                    <button type="button" class="layui-btn layui-btn-normal chooseFile">选择多文件</button>
                    <button type="button" class="layui-btn" id="uploadAction" style="margin-left: 10px">开始上传</button>

                    <div class="layui-upload-list" style="width: 90%;margin: auto;">
                        <table class="layui-table">
                            <colgroup>
                                <col width="150">
                                <col width="150">
                                <col width="150">
                                <col width="200">
                                <col width="150">
                            </colgroup>
                            <thead>
                            <tr><th>预览图</th><th>文件名</th>
                                <th>大小</th>
                                <th>上传进度</th>
                                <th>操作</th>
                            </tr></thead>
                            <tbody id="demoList"></tbody>
                        </table>
                    </div>

            </div>
        </div>
    </div>
</div>

<script>
    layui.use(['upload', 'element', 'layer','form'], function(){
        var $ = layui.jquery
            ,upload = layui.upload
            ,element = layui.element
            ,form = layui.form
            ,layer = layui.layer;

        request('/admin/file/upload',{},'get').then((res)=>{
            if(res.code==0){
                layer.msg(res.msg,{
                    icon: 2,
                    time: 3000 //1秒关闭（如果不配置，默认是3秒）
                },function () {
                    parent.layer.closeAll()
                })
                return false;
            }
        })
        request('/admin/file/getCategory',{}).then((res)=>{
            var html = ''
            for(let i of res.data){
                html+=`<option value="${i.id}">${i.name}</option>`
            }
            $("#category").append(html)
            form.render()
        })
        //常规使用 - 普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: 'https://httpbin.org/post' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });

                element.progress('demo', '0%'); //进度条复位
                layer.msg('上传中', {icon: 16, time: 0});
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                //……
                $('#demoText').html(''); //置空上传失败的状态
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
            //进度条
            ,progress: function(n, elem, e){
                element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                if(n == 100){
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });
        var count = 0;
        //演示多文件列表
        var uploadListIns = upload.render({
            elem: '.chooseFile'
            ,elemList: $('#demoList') //列表元素对象
            ,url: '/admin/file/upload'
            ,headers:{
                'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                'accept':'*/*'
            }
            ,accept: 'file'
            ,method:'post'
            ,multiple: true
            ,data:{
                category_id:function(){
                    return $('select[name="category_id"]').val()
                }
            }
            ,number: 3
            ,auto: false
            ,bindAction: '#uploadAction'
            ,choose: function(obj){
                var that = this;
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    console.log(file)

                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td><div class="layer-photos"><img width="100" height="100" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"></div></td>'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                        ,'<td><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload ">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    that.elemList.append(tr);
                    layer.photos({
                        photos: '.layer-photos'
                        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                    });
                    element.render('progress'); //渲染新加的进度条组件
                });
            }
            ,done: function(res, index, upload){ //成功的回调
                var that = this;
                console.log('rrr',res)
                if(res.code == 1){ //上传成功
                    var tr = that.elemList.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(3).html('100%'); //清空操作
                    delete this.files[index]; //删除文件队列已经上传成功的文件
                    count++
                    return;
                }else{
                    layer.msg(res.msg)
                    this.error(index, upload);
                    return false;
                }


            }
            ,allDone: function(obj){ //多文件上传完毕后的状态回调
                console.log(obj)
                if(obj.successful==count){
                    parent.layui.layer.closeAll()
                    parent.layui.table.reload('dataTable')
                }
            }
            ,error: function(index, upload){ //错误回调
                console.log('dd',index)

                var that = this;
                var tr = that.elemList.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
            ,progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
                element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
            }
        });

        //多图片上传
        upload.render({
            elem: '#test2'
            ,url: '' //此处配置你自己的上传接口即可
            ,multiple: true
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                });
            }
            ,done: function(res){
                //上传完毕
            }
        });

        //指定允许上传的文件类型
        upload.render({
            elem: '#test3'
            ,url: '' //此处配置你自己的上传接口即可
            ,accept: 'file' //普通文件
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res);
            }
        });
        upload.render({ //允许上传的文件后缀
            elem: '#test4'
            ,url: '' //此处配置你自己的上传接口即可
            ,accept: 'file' //普通文件
            ,exts: 'zip|rar|7z' //只允许上传压缩文件
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });
        upload.render({
            elem: '#test5'
            ,url: '' //此处配置你自己的上传接口即可
            ,accept: 'video' //视频
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });
        upload.render({
            elem: '#test6'
            ,url: '' //此处配置你自己的上传接口即可
            ,accept: 'audio' //音频
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });

        //设定文件大小限制
        upload.render({
            elem: '#test7'
            ,url: '' //此处配置你自己的上传接口即可
            ,size: 60 //限制文件大小，单位 KB
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });

        //同时绑定多个元素，并将属性设定在元素上
        upload.render({
            elem: '.demoMore'
            ,before: function(){
                layer.tips('接口地址：'+ this.url, this.item, {tips: 1});
            }
            ,done: function(res, index, upload){
                var item = this.item;
                console.log(item); //获取当前触发上传的元素，layui 2.1.0 新增
            }
        })

        //选完文件后不自动上传
        upload.render({
            elem: '#test8'
            ,url: '' //此处配置你自己的上传接口即可
            ,auto: false
            //,multiple: true
            ,bindAction: '#test9'
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });

        //拖拽上传
        upload.render({
            elem: '#test10'
            ,url: 'https://httpbin.org/post' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            ,done: function(res){
                layer.msg('上传成功');
                layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.files.file);
                console.log(res)
            }
        });

        //绑定原始文件域
        upload.render({
            elem: '#test20'
            ,url: '' //此处配置你自己的上传接口即可
            ,done: function(res){
                layer.msg('上传成功');
                console.log(res)
            }
        });

    });
</script>

</body>
</html>